from selenium import webdriver
from selenium.webdriver import ActionChains
import os
import pyautogui
import time
import re
import sys
from bs4 import BeautifulSoup
from selenium.common.exceptions import NoSuchElementException
import subprocess
"""
Bv = []
link_without_add1 = str(input("Please press the link:"))
def test(link_without_add):
    global link
    global k
    link = link_without_add.replace("?","")
    _ = re.findall("https://space.bilibili.com/[0-9]*/favlistfid=",link)
    k = 3
    if _ == []:
        _ = re.findall("https://space.bilibili.com/[0-9]*/video",link)
        k = 5
        if _ == []:
            print("Wrong String!Please repress!")
            k = 0
            while True:
                global link_without_add1
                link_without_add1 = str(input("Please press the link:"))
                link = link_without_add1.replace("?","")
                _ = re.findall("https://space.bilibili.com/[0-9]*/favlistfid=",link)
                k = 3
                if _ != []:
                    break
                else:
                    _ = re.findall("https://space.bilibili.com/[0-9]*/video",link)
                    k = 5
                    if _ != []:
                        break
                    else:
                        print("Wrong String!Please repress!")
                        k = 0

def roll_webpage():
    for _ in range(5):
        time.sleep(0.75)
        browser.execute_script('window.scrollBy(0,300)')

test(link_without_add1)
if not link_without_add1[27].isdecimal():
    print("Wrong String!Please repress!")
    while True:
        link_without_add1 = str(input("Please press the link:"))
        test(link_without_add1)
        if link_without_add1[27].isdecimal():
            break

browser = webdriver.Chrome(executable_path="chromedriver.exe")
browser.maximize_window()
browser.get(link.replace("favlist","favlist?"))
time.sleep(1)

def video_d_of_space(ask):
    roll_webpage()
    try:
        _ = browser.find_element_by_xpath('//*[@id="page-video"]/div/div[2]/div[1]/div[1]/p')
    except NoSuchElementException:
        print("t")
        sys.exit()
    text = browser.page_source
    soup = BeautifulSoup(text, "lxml")
    if ask == 1:
        global number,page_number
        number = int(str(soup.find(class_="count").text))
        if number == 0:
            browser.quit()
            print("There's no video in this space!")
            sys.exit()
        page_number = int(soup.find(class_="be-pager-total").string.replace("共 ","").replace(" 页，",""))
    elif ask == 3 or ask == 0:
        for i in soup.find_all(class_="small-item"):
            Bv.append(i["data-aid"])
    if ask == 0:
        browser.find_element_by_class_name("be-pager-next").click()

def video_d_of_favlist(ask):
    roll_webpage()
    try:
        _ = browser.find_element_by_xpath('//*[@id="page-fav"]/div[1]/div[2]/div[1]/div/div/div[3]/a')
    except NoSuchElementException:
        print("Nothing!Please try again!")
        sys.exit()
    text = browser.page_source
    soup = BeautifulSoup(text, "lxml")
    if ask == 1:
        global number_fav,page_number_fav
        number_fav = str(soup.find_all(class_="fav-meta")[1].text).split("个内容")[0]
        if number_fav == '0':
            browser.quit()
            print("There's no video in this favlist!")
            sys.exit()
        elif number_fav == 'NaN':
            print("This is a wrong link!")
            sys.exit()
        else:
            number_fav = int(number_fav)
        page_number_fav = int(soup.find(class_="be-pager-total").string.replace("共 ","").replace(" 页，",""))
    elif ask == 3 or ask == 0:
        try:
            for i in soup.find_all(class_="small-item"):
                Bv.append(i["data-aid"])
        except NoSuchElementException:
            print("There's no video in this favlist!")
            sys.exit()
    if Bv == []:
        print("There's no video in this favlist!")
        sys.exit()
    if ask == 0:
        browser.find_element_by_class_name("be-pager-next").click()

if k == 3:
    video_d_of_favlist(1)
    for _ in range(page_number_fav-1):
        video_d_of_favlist(0)
        time.sleep(1.5)
    video_d_of_favlist(3)
    # Bv = [Bv[n] for n in range(len(Bv)) if n > 19]
    if len(Bv) != number_fav:
        print("Something's wrong!You may need to restart this programme.")
        sys.exit()
    browser.quit()
if k == 5:
    video_d_of_space(1)
    for _ in range(page_number-1):
        video_d_of_space(0)
        time.sleep(1.5)
    video_d_of_space(3)
    # Bv = [Bv[n] for n in range(len(Bv)) if n > 29]
    if len(Bv) != number:
        print("Something's wrong!You may need to restart this programme.")
        sys.exit()
    browser.quit()
"""
Bv = ['BV1Gq4y1T7V6', 'BV1jL4y1Y7iX', 'BV1PQ4y127AF', 'BV1gf4y1H7yX', 'BV1SL411b7NB']
# os.system("JiJiDownForWPF.exe &")
subprocess.run("JiJiDownForWPF.exe")
print("Hello, World!")
time.sleep(4)
for i in Bv:
    pyautogui.click(395,200,duration=0.5)
    pyautogui.click(855,530,duration=0.5)
    pyautogui.dragTo(468, 521)
    pyautogui.press('backspace')
    pyautogui.typewrite(i)
    time.sleep(1.5)
    pyautogui.typewrite(['enter', 'enter'], interval=1)
    pyautogui.click(452,588,duration=0.75)
    time.sleep(1)
